<template>
	<view class="share-poster" v-if="show">
		<view class="mask" :class="{ on: showanim }" v-if="postshow"></view>
		<view class="mask" :class="{ on: showanim }" @click="hideshare('show')" v-else></view>

		<view class="toaskboxs" v-if="!posterImage" :class="{ on: showanim }">
			<view class="rows">
				<view class="tt">立即分享给好友</view>
				<view class="flex-center">
					<button type="button" class="item" open-type="share" id="1" :data-code="code" :data-type="sharetype">
						<view class="icon flex-center">
							<image src="/static/images/powechat_icon.png" mode="aspectFill" class="imgs"></image>
						</view>
						<view class="subtitle">分享给微信好友</view>
					</button>
					<!-- v-if="!posterImage" -->
					<view class="item" @click="shareFc()">
						<view class="icon flex-center">
							<image src="/static/images/postergx_icon.png" mode="aspectFill" class="imgs"></image>
						</view>
						<view class="subtitle">生成海报</view>
					</view>
					<!-- <view class="item " @click="saveImage()" v-else>
						<view class="icon flex-center"><image src="/static/images/down_icon.png" mode="aspectFill" class="imgs"></image></view>
						<view class="subtitle">保存图片</view>
					</view> -->
				</view>
			</view>
			<view class="toolbtns flex-center" @click="hideshare('show')">取消</view>
		</view>

		<view class="share-imgs" :class="{ on: postshowanim }" v-if="postshow">
			<view class="share-box">
				<scroll-view class="scroll_y flex-center" :scroll-y="true">
					<view class="boxsimg">
						<image @click="hideshare('show')" class="gbimg" src="/static/images/com_close.png" mode="heightFix"></image>
						<image :src="posterImage" class="imgs" mode="widthFix"></image>
						<view @click="saveImage()" class="btns flex-center">保存图片</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<view class="hideCanvasView">
			<canvas
				class="hideCanvas"
				:id="canvasId"
				:canvas-id="canvasId"
				:style="{
					width: (poster.width || 10) + 'px',
					height: (poster.height || 10) + 'px',
				}"
			></canvas>
		</view>
	</view>
</template>

<script>
import _app from '@/util/QS-SharePoster/app.js';
import { getSharePoster } from '@/util/QS-SharePoster/QS-SharePoster.js';
import storeMixin from '@/store/storeMixin';
export default {
	mixins: [storeMixin],
	name: 'share-poster',
	props: {
		item: {
			type: Object,
			default() {
				return {};
			},
		},
		shareurl: {
			type: String,
			default: '',
		},
		/*---0为抽签：抽签进行地如火如荼, 还不赶快来参与
			1为抽盒：我在怼隐藏，快来助我一臂之力！
			2为抽选：欧皇保佑，这一次，救救孩子！
			3为商城：安利一个新娃 真香！
			4为一番赏：我在抽欧气一番赏，快来祝我一臂之力
			5为助力红包：来助我一发入魂吧！
		---*/
		code: {
			type: Number,
			default: 0,
		},
		sharetype: {
			type: String,
			default: '',
		},
	},
	data() {
		return {
			show: false,
			showanim: false,
			postshow: false,
			postshowanim: false,
			canvasId: 'default_PosterCanvasId',
			posterImage: '',
			poster: {},
			codetext: [
				'抽签进行地如火如荼, 还不赶快来参与',
				'我在怼隐藏，快来助我一臂之力！',
				'小伙伴, 一起来玩玩呗~',
				'安利一个新娃 真香！',
				'我在抽TOYZERO一番赏，快来祝我一臂之力',
				'来助我一发入魂吧！',
			],
		};
	},
	created() {},
	methods: {
		showshare(key = 'show') {
			if (this[key]) {
				return;
			}
			this[key] = true;
			setTimeout(() => {
				this[`${key}anim`] = true;
			}, 10);
		},

		hideshare(key = 'show') {
			if (!this[`${key}anim`]) {
				return;
			}
			this[`${key}anim`] = false;
			setTimeout(() => {
				this[key] = false;
			}, 300);
		},

		async shareFc() {
			let zheight = 0;
			let _this = this;
			let priceText = `¥${this.item.minprice || '0.00'}`;
			if (this.code == 2) {
				priceText = `¥${this.item.price || '0.00'}`;
			}
			try {
				const d = await getSharePoster({
					_this: this, //若在组件中使用 必传
					type: 'customType',
					formData: {
						//访问接口获取背景图携带自定义数据
					},
					posterCanvasId: this.canvasId, //canvasId
					delayTimeScale: 20, //延时系数
					background: {
						width: 598,
						height: 900,
						backgroundColor: '#ffffff',
					},
					drawArray: ({
						bgObj, //背景图对象
						type, //自己设置的自定义标识
						bgScale, //背景缩放
						setBgObj, //动态设置画布(宽高),若使用该方法不建议背景图方式绘制, 建议使用background自定义画布绘制, 因为这个方法绘制修改背景图的宽高
						getBgObj,
					}) => {
						const dx = bgObj.width * 0.3;
						const fontSize = bgObj.width * 0.045;
						const lineHeight = bgObj.height * 0.04;
						//可直接return数组，也可以return一个promise对象, 但最终resolve一个数组, 这样就可以方便实现后台可控绘制海报
						return new Promise((rs, rj) => {
							rs([
								{
									type: 'image',
									id: 'Image',
									url: `${this.item.image30 || this.item.image}`,
									dx: 0,
									dy: 0,
									dWidth: 622,
									dHeight: 622,
								},
								{
									type: 'text',
									id: 'Title',
									text: `${this.item.title}`,
									size: 32,
									color: '#090406',
									allInfoCallback({ drawArray }) {
										const imageInfo = drawArray.find(item => item.id === 'Image');
										return {
											lineFeed: {
												maxWidth: 310,
												lineHeight: 40,
											},
											dy: imageInfo.dHeight + 70,
										};
									},
									infoCallBack(textLength, a) {
										let len = bgObj.width - textLength;
										let linenum = Math.ceil(textLength / 310);
										return {
											dx: 26,
											dHeight: Math.ceil(textLength / 310) * 40,
											textAlign: 'left',
										};
									},
								},
								{
									type: 'text',
									id: 'text3',
									text: `${priceText || '0.00'}`,
									size: '30',
									color: '#1FD1C2',
									dx: 26,
									allInfoCallback({ drawArray }) {
										const titleInfo = drawArray.find(item => item.id === 'Title');
										return {
											dy: titleInfo.dy + titleInfo.dHeight + 15,
										};
									},
								},
								{
									type: 'qrcode',
									id: 'Qrcode',
									text: _this.webUrl + '/mp/go?path=' + encodeURIComponent(this.shareurl),
									size: 180,
									background: '#ffffff',
									dx: 380,
									allInfoCallback({ drawArray }) {
										const imageInfo2 = drawArray.find(item => item.id === 'Image');
										zheight = imageInfo2.dHeight + 250;
										return {
											dy: imageInfo2.dHeight + 30,
										};
									},
								},
							]);
						});
					},
					setCanvasWH: ({ bgObj, type, bgScale }) => {
						bgObj.height = zheight;
						this.poster = bgObj;
					},
				});
				this.posterImage = d.poster.tempFilePath;
				this.showshare('postshow');
			} catch (e) {
				_app.hideLoading();
				_app.showToast(JSON.stringify(e));
			}
		},

		saveImage() {
			// let _this = this;
			// uni.saveImageToPhotosAlbum({
			// 	filePath: this.posterImage,
			// 	success(res) {
			// 		_app.showToast('保存成功');
			// 		_this.hideshare();
			// 	},
			// 	fail(err) {}
			// });

			let _this = this;
			uni.authorize({
				scope: 'scope.writePhotosAlbum',
				success() {
					uni.saveImageToPhotosAlbum({
						filePath: _this.posterImage,
						success(res) {
							_app.showToast('保存成功');
							_this.hideshare();
						},
						fail(err) {},
					});
				},
				fail(res2) {
					uni.getSetting({
						success(res2) {
							console.log(res2.authSetting);
							if (!res2.authSetting['scope.writePhotosAlbum']) {
								uni.showModal({
									title: '您已拒绝获取相册权限',
									content: '是否进入权限管理，调整授权？',
									success: res => {
										if (res.confirm) {
											uni.openSetting({
												success: res => {
													uni.saveImageToPhotosAlbum({
														filePath: _this.posterImage,
														success(res) {
															_app.showToast('保存成功');
															_this.hideshare();
														},
														fail(err) {},
													});
												},
											});
										} else if (res.cancel) {
											return uni.showToast({
												title: '已取消！',
											});
										}
									},
								});
							}
						},
					});
				},
			});
		},
	},
	watch: {
		showanim(newVal) {
			if (!newVal && this.postshow) {
				this.hideshare('postshow');
				this.posterImage = '';
			}
		},
	},
};
</script>

<style lang="scss">
.share-poster {
	width: 100%;
	height: 100%;
	position: fixed;
	left: 0;
	top: 0;
	z-index: 99999;

	.mask {
		width: 100%;
		height: 100%;
		background: rgba($color: #000000, $alpha: 0.76);
		opacity: 0;
		visibility: hidden;
		transition: all 0.4s ease;
		position: absolute;
		left: 0;
		top: 0;
		z-index: 1;

		&.on {
			opacity: 1;
			visibility: visible;
		}
	}

	.cancelBtn {
		width: 128rpx;
		height: 76rpx;
		position: fixed;
		top: 40rpx;
		right: 0;
		z-index: 3;
		transform: translate(100%);
		transition: transform 0.3s ease;

		&.on {
			transform: translate(0%);
		}

		.imgs {
			width: 100%;
			height: 100%;
		}
	}

	.toaskboxs {
		width: 100%;
		height: 400rpx;
		background: #ffffff;
		border-radius: 48rpx 48rpx 0 0;
		transition: transform 0.3s ease;
		transform: translateY(100%);
		position: absolute;
		left: 0;
		bottom: 0;
		z-index: 2;

		&.on {
			transform: translateY(0);
		}

		.rows {
			position: relative;
			height: 280rpx;
			box-sizing: border-box;
			padding-top: 36rpx;

			.tt {
				color: #1c1c1c;
				font-size: 28rpx;
				text-align: center;
				margin-bottom: 32rpx;
			}

			.item {
				width: 230rpx;
				margin: 0;
				padding: 0;
				background: none;
				line-height: 1;

				.icon {
					margin: 0 auto;
					width: 102rpx;
					height: 102rpx;
					border-radius: 50%;

					.imgs {
						width: 102rpx;
						height: 102rpx;
						display: block;
					}
				}

				.subtitle {
					font-size: 22rpx;
					color: #595959;
					text-align: center;
					margin-top: 8rpx;
					height: 34rpx;
					line-height: 34rpx;
				}
			}
		}

		.toolbtns {
			width: 100%;
			height: 100rpx;
			line-height: 100rpx;
			background: #fff;
			color: #9a9a9a;
			text-align: center;
			border-top: 20rpx solid #f6f6f6;
		}
	}

	.share-imgs {
		width: 100%;
		height: 100vh;
		opacity: 0;
		transition: all 0.4s ease;
		position: absolute;
		transform: scale(1.2);
		left: 0;
		top: 0;
		z-index: 2;

		.share-box {
			width: 100%;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			box-sizing: border-box;
		}

		&.on {
			opacity: 1;
			transform: scale(1);
		}

		.scroll_y {
			height: 100%;

			.imgs {
				width: 100%;
				height: 900rpx;
			}
		}

		.boxsimg {
			padding: 242rpx 76rpx 104rpx;
			position: relative;

			.gbimg {
				width: 100rpx;
				height: 136rpx;
				display: block;
				position: absolute;
				top: 104rpx;
				right: 0;
				z-index: 10;
			}

			.imgs {
				width: 100%;
				border-radius: 24rpx;
				display: block;
			}

			.btns {
				color: #ffffff;
				font-size: 30rpx;
				width: 300rpx;
				height: 88rpx;
				line-height: 88rpx;
				border: 2rpx solid #ffffff;
				border-radius: 44rpx;
				background-color: transparent;
				margin: 48rpx auto 0;
			}
		}
	}
}

.hideCanvasView {
	position: relative;
}

.hideCanvas {
	position: fixed;
	top: -99999upx;
	left: -99999upx;
	z-index: -99999;
}

@supports (bottom: env(safe-area-inset-bottom)) {
	.share-poster {
		.toaskboxs {
			height: calc(400rpx + env(safe-area-inset-bottom));
		}
	}
}
</style>
